package com.apkplugthemedemo;
import java.io.File;
import java.util.List;
import org.apkplug.Bundle.BundleControl;
import org.apkplug.Bundle.OnThemeChengeListener;
import org.apkplug.Bundle.RegThemeChengeListener;
import org.apkplug.Bundle.installCallback;
import org.apkplug.app.FrameworkFactory;
import org.apkplug.app.FrameworkInstance;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleEvent;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceListener;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.framework.SynchronousBundleListener;
import com.apkplug.Service.ThemeCheng;
import com.apkplug.adapter.ListBundleAdapter;
import android.os.Bundle;
import android.os.Environment;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.KeyEvent;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
/**
 * 0.0.1 版本新增安装本地插件接口
 * MainActivity.install(String path,installCallback callback)
 * @author 梁前武 qq 1587790525
 * www.apkplug.com
 */
public class MainActivity extends Activity {
	private FrameworkInstance frame=null;
	private List<org.osgi.framework.Bundle> bundles=null;
	private TextView info=null;
	private ListView bundlelist =null;
	private ListBundleAdapter adapter=null;
	private ServiceReference ref=null;
	private Button installlocal=null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		info =(TextView)this.findViewById(R.id.info);
		installlocal=(Button) this.findViewById(R.id.installlocal);
		if(ThemeChengFactory.service!=null)
			installlocal.setBackgroundResource(ThemeChengFactory.service.buttonStyle());
		frame=((ProxyApplication)this.getApplication()).getFrame();
		initBundleList();
		ListenerTheme();
		//监听插件安装状态已动态更新列表
		ListenerBundleEvent();
		
	}
	@SuppressLint("NewApi")
	public void ListenerTheme(){
		BundleContext context=frame.getSystemBundleContext();
		ServiceReference reference=context.getServiceReference(RegThemeChengeListener.class.getName());
    	if(null!=reference){
    		final RegThemeChengeListener service=(RegThemeChengeListener) context.getService(reference);
    		if(service!=null){
    			//插件启动级别为1(会自启) 并且不检查插件版本是否相同都安装
    			service.registerOnThemeListener(
    					new OnThemeChengeListener(){
							@SuppressLint("NewApi")
							@Override
							public void afterChenged(
									org.osgi.framework.Bundle arg0, int arg1) {
								MainActivity.this.recreate();
								service.unregisterOnThemeListener(this);
							}

							@Override
							public void beforeChenge(
									org.osgi.framework.Bundle bb, int arg1,org.osgi.framework.Bundle tob, int arg2) {
								
							}
    			});
    		}
    		context.ungetService(reference);
    	}
		try {
			frame.getSystemBundleContext().addServiceListener(
					new ServiceListener(){
						@Override
						public void serviceChanged(ServiceEvent event) {
							switch  (event.getType()) {
								case  ServiceEvent.REGISTERED:
									if  (ref  ==   null ) {
										System.out.println("主题切换服务");
										ref  =  event.getServiceReference();
										ThemeChengFactory.service  =  (ThemeCheng) frame.getSystemBundleContext().getService(ref);//保存实例以备后续访问
									}
									break ;
								case  ServiceEvent.UNREGISTERING:
									if  (ref  ==  event.getServiceReference()) {
										frame.getSystemBundleContext().ungetService(ref); //释放实例 
										ThemeChengFactory.service  =   null ;
											ref  =   null ;
									}
									break ;
								}
							
						}
			},"(objectclass=com.apkplug.Service.ThemeCheng)" );
		} catch (InvalidSyntaxException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
	}
	/**
	 * 初始化显示已安装插件的UI
	 */
	public void initBundleList(){
		 //已安装插件列表
        bundlelist=(ListView)findViewById(R.id.bundlelist);
		bundles=new java.util.ArrayList<org.osgi.framework.Bundle>();
		BundleContext context =frame.getSystemBundleContext();
		for(int i=0;i<context.getBundles().length;i++)
		{
			if(context.getBundles()[i].getBundleId()!=0){
				//获取已安装插件
				bundles.add(context.getBundles()[i]);   
			}       	        
		}
		adapter=new ListBundleAdapter(MainActivity.this,bundles);
		bundlelist.setAdapter(adapter);
	}
	
	/**
	 * 监听插件安装事件，当有新插件安装或卸载时成功也更新一下
	 */
 	public void ListenerBundleEvent(){
 		frame.getSystemBundleContext()
			.addBundleListener(
					new SynchronousBundleListener(){
	
						public void bundleChanged(BundleEvent event) {
							//把插件列表清空
							bundles.clear();
							BundleContext context =frame.getSystemBundleContext();
							for(int i=0;i<context.getBundles().length;i++)
							{
								if(context.getBundles()[i].getBundleId()!=0){
									bundles.add(context.getBundles()[i]);        	        
								}
							}
							adapter.notifyDataSetChanged();
						}
					
			});
	}
	
 	public boolean dispatchKeyEvent(KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK
				&& event.getAction() != KeyEvent.ACTION_UP) {
			AlertDialog.Builder alertbBuilder = new AlertDialog.Builder(this);
			alertbBuilder
					.setTitle("退出应用")
					.setMessage("你确定要退出程序?")
					.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									//MyProperty中调试模式设置为true调用shutdown将清理已安装插件缓存
									//以在下次启动时重新安�?
									frame.shutdown();
									int nPid = android.os.Process.myPid();
									android.os.Process.killProcess(nPid);
								}
							})
					.setNegativeButton("取消",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.cancel();
								}
							}).create();
			alertbBuilder.show();
			return true;
		} else {
			return super.dispatchKeyEvent(event);
		}
	} 
}
